package com.ygqh.baby.service.impl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.crazycake.shiro.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.model.Token;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.WxSmallTokenStorager;
import com.ygqh.baby.service.YgOrderLogService;
import com.ygqh.baby.utils.DateConvertUtils;

@Repository
public class WxSmallTokenStoragerImpl implements WxSmallTokenStorager {
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	private static String WX_TOKEN_STORAGER = "WX_SAMLL_TOKEN_STORAGER";
	private static final Logger logger = Logger.getLogger(WxSmallTokenStoragerImpl.class);

	@Override
	public Token lookup(String cacheKey) throws WeixinException {
		logger.info("token-cache-key:" + cacheKey);
		long currentTimeMillis = System.currentTimeMillis();
		Token result = (Token) SerializeUtils.deserialize(redisDao.get((WX_TOKEN_STORAGER + cacheKey).getBytes()));
		if (result != null) {
			System.out.println("小程序—token 创建时间：" + result.getCreateTime() + ";" + DateConvertUtils.formatDateTime(new Date(result.getCreateTime())));
			System.out.println("当前时间：" + currentTimeMillis + ";" + DateConvertUtils.formatDateTime(new Date(currentTimeMillis)));
			if (result.getExpiresIn() > 0 && currentTimeMillis > (result.getExpiresIn() * 1000 + result.getCreateTime() - 30 * 1000)) {// 验证有时间限制的token数据，避免时间误差，提前30秒作废
				logger.info("过期缓存" + cacheKey + ":" + result);
				return null;
			}
		}
	/*	ygOrderLogService.addOrderLog(
				99l,
				OrderStatus.TradeClosed,
				"token",
				"当前时间：" + currentTimeMillis + ";" + DateConvertUtils.formatDateTime(new Date(currentTimeMillis)) + ";【Token】："
						+ (result == null ? "" : result.toString()));*/
		return result;
	}

	@Override
	public void caching(String cacheKey, Token t) throws WeixinException {
		logger.info("缓存" + cacheKey + ":" + t);
		System.out.println(t.toString());
		redisDao.set((WX_TOKEN_STORAGER + cacheKey).getBytes(), SerializeUtils.serialize(t), 7000 * 1000);// 提前200秒失效
	}

	@Override
	public void clear() {
		this.clear();
	}

	@Override
	public Token evict(String arg0) {
		return this.evict(arg0);
	}

}
